package com.spring.framework.transaction.listener;

import com.spring.framework.transaction.model.TxStudy;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.FileNotFoundException;

@Component
@SuppressWarnings("all")
public class EventService {
	/**
	 * 直接注入ApplicationEventPublisher，用于发布事件
	 */
	@Resource
	private ApplicationEventPublisher applicationEventPublisher;
	/**
	 * jdbc模版，用于操作数据库
	 */
	@Resource
	private JdbcTemplate jdbcTemplate;

	//为了简单，直接在Service中进行数据库访问

	/**
	 * 这个结果也印证了Spring事务的默认回滚规则，只有在抛出RuntimeException和Error级别的异常时才会回滚，如果是其他异常比如受检
	 * 异常，则不会回滚而是提交！
	 */
	@Transactional
	// @Transactional(rollbackFor = Exception.class)
	public void select() throws FileNotFoundException {
		applicationEventPublisher.publishEvent("查询数据");
		String sql = "select * from tx_study where id = ?";
		System.out.println(jdbcTemplate.queryForObject(sql, BeanPropertyRowMapper.newInstance(TxStudy.class), 1));
		// throw new RuntimeException();
		// throw new FileNotFoundException();
	}
}
